import 'package:amway_superapp_creator_plugin/analysis/zhuge_edit.dart';
import 'package:amway_superapp_creator_plugin/config/colors_config.dart';
import 'package:amway_superapp_creator_plugin/dialog/comm_tip_dialog.dart';
import 'package:amway_superapp_creator_plugin/models/tag_item_bean.dart';
import 'package:amway_superapp_creator_plugin/utils/colors_util.dart';
import 'package:amway_superapp_creator_plugin/utils/toast_util.dart';
import 'package:amway_superapp_creator_plugin/view_state.dart';
import 'package:amway_superapp_creator_plugin/viewmodels/tag_list_viewmodel.dart';
import 'package:amway_superapp_creator_plugin/views/base_view.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';

/// @descriptions: 客户标签展示页
/// @author: liya
/// @date: 2020-10-13
/// version: 1.0
class TagListPage extends StatelessWidget {
  int _pageType = 0;
  List<String> _cachedMarks = new List();

  TagListPage(String pageType, [List<String> cachedMarks]) {
    this._pageType = int.parse(pageType);
    if (cachedMarks != null) {
      _cachedMarks.addAll(cachedMarks);
    }
  }

  Widget _buildSingleTag(
      TagItemBean bean, bool isShowDelete, TagListVM viewModel) {
    Widget _buildDeleteButton() {
      return Positioned(
        right: 0,
        top: 0,
        child: GestureDetector(
          onTap: () {
            bean.isSelected = false;
            viewModel.remove(bean);
          },
          child: new Image.asset('picture/icon_tag_delete.png',
              width: ScreenUtil().setWidth(18),
              height: ScreenUtil().setWidth(18),
              package: 'amway_superapp_creator_plugin'),
        ),
      );
    }

    return Stack(
      children: [
        Container(
          child: FlatButton(
            minWidth: ScreenUtil().setSp(110),
            onPressed: () {
              // if (!bean.isSelected && viewModel.collectionList.length < 3) {
              //   bean.isSelected = true;
              //   viewModel.add(bean);
              // } else {
              //   bean.isSelected = false;
              //   viewModel.remove(bean);
              // }
            },
            shape: RoundedRectangleBorder(
                borderRadius:
                BorderRadius.circular(ScreenUtil().setHeight(18))),
            color: bean.isSelected
                ? ColorUtil.fromHex('#FFE9F7F8').withOpacity(0.9)
                : ColorUtil.fromHex('#F7F7F7FF'),
            child: Text(
              bean.title,
              style: TextStyle(
                  fontSize: ScreenUtil().setSp(14),
                  color: Colors.black.withOpacity(0.5)),
            ),
          ),
          height: ScreenUtil().setSp(36),
        ),
        _buildDeleteButton()
      ],
      fit: StackFit.loose,
    );
  }

  Widget _buildBottomGridView(List<TagItemBean> beans, TagListVM viewModel) {
    if (beans.length > 0) {
      return Container(
          width: double.infinity,
          decoration: BoxDecoration(color: Colors.white, boxShadow: [
            BoxShadow(
                offset: Offset(0, ScreenUtil().setHeight(-2)),
                blurRadius: ScreenUtil().setHeight(15),
                color: ColorUtil.fromHex('#26000000'))
          ]),
          alignment: Alignment.centerLeft,
          padding: EdgeInsets.symmetric(
              horizontal: ScreenUtil().setSp(24),
              vertical: ScreenUtil().setSp(24)),
          child: viewModel.pageType == 0
              ? Wrap(
            alignment: WrapAlignment.start,
            spacing: ScreenUtil().setHeight(18),
            crossAxisAlignment: WrapCrossAlignment.center,
            runAlignment: WrapAlignment.start,
            runSpacing: ScreenUtil().setHeight(18),
            children: List.generate(
                beans.length,
                    (index) => _buildSingleTag(
                    beans.elementAt(index), true, viewModel)),
          )
              : Row(
            mainAxisSize: MainAxisSize.max,
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.start,
            children: List.generate(
                beans.length,
                    (index) => Padding(
                  padding: EdgeInsets.fromLTRB(
                      index == 1 ? ScreenUtil().setWidth(18) : 0,
                      0,
                      index == 1 ? ScreenUtil().setWidth(18) : 0,
                      0),
                  child: _buildSingleTag(
                      beans.elementAt(index), true, viewModel),
                )),
          ));
    } else {
      return new Container(width: 0, height: 0);
    }
  }

  Widget _buildGridView(
      List<TagItemBean> beans, bool isShowDelete, TagListVM viewModel) {
    List<Widget> widgetList = List.generate(
        beans.length,
            (index) => Container(
          child: FlatButton(
            minWidth: ScreenUtil().setSp(110),
            onPressed: () {
              if (!beans[index].isSelected &&
                  viewModel.collectionList.length < 3) {
                beans.elementAt(index).isSelected = true;
                viewModel.add(beans.elementAt(index));
              } else {
                beans.elementAt(index).isSelected = false;
                viewModel.remove(beans.elementAt(index));
              }
            },
            shape: RoundedRectangleBorder(
                borderRadius:
                BorderRadius.circular(ScreenUtil().setSp(18))),
            color: beans.elementAt(index).isSelected
                ? ColorUtil.fromHex('#FFE9F7F8').withOpacity(0.9)
                : viewModel.collectionList.length < 3
                ? ColorUtil.fromHex('#F7F7F7FF')
                : ColorsConfig.c_F7F7F7.withOpacity(0.5),
            child: Text(
              beans.elementAt(index).title,
              style: TextStyle(
                  fontSize: ScreenUtil().setSp(14),
                  color: ColorsConfig.c_2c2c2c
                      .withOpacity(beans.elementAt(index).isSelected
                      ? 0.5
                      : viewModel.collectionList.length < 3
                      ? 0.5
                      : 0.2)),
            ),
          ),
          height: ScreenUtil().setSp(36),
        ));

    if (beans.length > 0) {
      if (viewModel.pageType == 1) {
        return GridView.count(
          physics: NeverScrollableScrollPhysics(),
          // 创建几列
          crossAxisCount: 3,
          // Axis.horizontal表示横向滑动，scrollDirection: Axis.vertical表示纵向滑动
          scrollDirection: Axis.vertical,
          // 列之间的间距
          crossAxisSpacing: ScreenUtil().setSp(24),
          // 行之间的间距
          mainAxisSpacing: ScreenUtil().setSp(18),
          // 默认false 是否根据子孩子的宽高自动包裹item自身
          shrinkWrap: true,
          // true表示数据倒序排列 false表示顺序排列
          reverse: false,
          // 子孩子的比例
          childAspectRatio: 110 / 36,
          // 设置子孩子item,这里传入子孩子控件
          children: widgetList,
        );
      } else {
        return Wrap(
          spacing: ScreenUtil().setSp(18),
          alignment: WrapAlignment.start,
          crossAxisAlignment: WrapCrossAlignment.center,
          runAlignment: WrapAlignment.start,
          runSpacing: ScreenUtil().setSp(18),
          children: widgetList,
        );
      }
    } else {
      return new Container(width: 0, height: 0);
    }
  }

  List<Widget> _buildIdentities(TagListVM viewModel) {
    List<Widget> widgetList = [];
    viewModel.identityList.forEach((key, value) {
      widgetList.add(Container(
        child: Text(
          key,
          style: TextStyle(
              color: ColorUtil.fromHex('#FF2C2C2C'),
              fontWeight: FontWeight.bold,
              fontSize: ScreenUtil().setWidth(18)),
        ),
        margin: EdgeInsets.only(
            top: ScreenUtil().setWidth(40), bottom: ScreenUtil().setWidth(18)),
      ));
      widgetList.add(_buildGridView(value, false, viewModel));
    });
    return widgetList;
  }

  List<Widget> _buildTagItems(TagListVM viewModel) {
    if (viewModel.pageType == 0) {
      return _buildIdentities(viewModel);
    } else {
      // return [_buildGridView(viewModel.hobbyList, false, viewModel)];
      return [_buildGridView(viewModel.hobbyList, false, viewModel),];
    }
  }

  Widget _buildTagGroup(TagListVM viewModel) {
    return Container(
      padding: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(24),
          viewModel.pageType == 0 ? 0 : ScreenUtil().setHeight(40),
          ScreenUtil().setWidth(24),
          ScreenUtil().setWidth(0)),
      child: ListView(
        padding: EdgeInsets.only(bottom: ScreenUtil().setHeight(20)),
        children: _buildTagItems(viewModel),
      ),
    );
  }

  void showBackDialog(BuildContext context) {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (_) {
          return CommTipDialog(
            content: '返回上一步会丢失当前已编辑信息，是否确认返回',
            confirmText: "知道了",
            confirmCallback: () {
              Navigator.of(context).pop();
            },
          );
        });
  }

  Color getBottomColor(TagListVM viewModel) {
    if (viewModel.pageType == 0) {
      ///身份标签
      if (viewModel.collectionList.length > 0) {
        return ColorsConfig.leftBackColor;
      } else {
        return ColorsConfig.leftBackColor.withOpacity(0.3);
      }
    } else {
      ///兴趣标签
      if (viewModel.collectionList.length == 3) {
        return ColorsConfig.leftBackColor;
      } else {
        return ColorsConfig.leftBackColor.withOpacity(0.3);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context,
        designSize: Size(414, 896), allowFontScaling: true);

    return BaseView<TagListVM>(
        model: TagListVM(_pageType, api: Provider.of(context)),
        onModelReady: (model) async {
          model.setData(_cachedMarks);
          ZhugeEditAnalysis.editPage(model.pageType==0?EditPageType.idTag:EditPageType.interestTag);

        },
        builder: (context, model, child) => WillPopScope(
          onWillPop: () async {
            if (!model.identicalToCache()) {
              showBackDialog(context);
            } else {
              Navigator.of(context).pop();
            }
            return true;
          },
          child: Scaffold(
            appBar: AppBar(
                backgroundColor: Colors.white,
                elevation: 0,
                //去除阴影
                brightness: Brightness.light,
                //黑色状态栏
                title: new Text(
                  model.pageType == 0 ? "选择身份标签" : "选择兴趣标签",
                  style: TextStyle(fontSize: 20, color: Colors.black),
                ),
                centerTitle: true,
                leading: GestureDetector(
                  child: BaseView.buildBackButton(),
                  onTap: () {
                    if (!model.identicalToCache()) {
                      showBackDialog(context);
                    } else {
                      Navigator.of(context).pop();
                    }
                  },
                )),
            body: model.state == ViewState.Busy
                ? Center(child: CircularProgressIndicator())
                : Container(
              color: Colors.white,
              child: Column(
                mainAxisSize: MainAxisSize.max,
                children: [
                  Padding(
                    padding: EdgeInsets.fromLTRB(
                        0,
                        ScreenUtil().setHeight(40),
                        0,
                        ScreenUtil().setHeight(6)),
                    child: Center(
                      child: new Text(
                        model.pageType == 0 ? "身份标签" : "兴趣标签",
                        style: TextStyle(
                            fontSize: ScreenUtil().setSp(36),
                            color: Colors.black),
                      ),
                    ),
                  ),
                  Center(
                    child: new Text(
                      model.pageType == 0
                          ? "请选择身份标签，让顾客朋友们更了解你"
                          : "请选择3个最符合您的兴趣标签",
                      style: TextStyle(
                          fontSize: ScreenUtil().setSp(12),
                          color: Colors.grey),
                    ),
                  ),
                  Expanded(child: _buildTagGroup(model)),
                  Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      _buildBottomGridView(model.collectionList, model),
                      Container(
                        width: double.maxFinite,
                        decoration: BoxDecoration(
                            color: Colors.white,
                            boxShadow: model.collectionList.length < 1
                                ? [
                              BoxShadow(
                                  offset:
                                  Offset(0, ScreenUtil().setHeight(-2)),
                                  blurRadius: ScreenUtil().setHeight(15),
                                  color: ColorUtil.fromHex('#26000000'))
                            ]
                                : [
                              BoxShadow(
                                  offset: Offset(0, 0),
                                  blurRadius: ScreenUtil().setHeight(10),
                                  color: ColorUtil.fromHex('#26000000'))
                            ]),
                        padding: EdgeInsets.fromLTRB(
                            ScreenUtil().setWidth(16),
                            ScreenUtil().setHeight(16),
                            ScreenUtil().setWidth(8),
                            ScreenUtil().setHeight(34)),
                        child: FlatButton(
                          height: ScreenUtil().setHeight(50),
                          shape: StadiumBorder(),
                          color: getBottomColor(model),
                          onPressed: () {
                            if (model.collectionList.length == 0) {
                              return;
                            }
                            if (model.pageType == 1 &&
                                model.collectionList.length < 3) {
                              ToastUtils.showShortToast('请最少选择三个标签哦！');
                              return;
                            }
                            List<String> result = new List();
                            model.collectionList.forEach((element) {
                              result.add(element.title);
                            });
                            if(model.pageType==0){
                              ZhugeEditAnalysis.idTagPageClickConfirm("身份标签选择");
                            }else{
                              ZhugeEditAnalysis.interestTagPageClickConfirm("兴趣标签选择");
                            }
                            Navigator.of(context).pop(result);

                          },
                          child: Text('完成(' +
                              model.collectionList.length.toString() +
                              '/3)'),
                          textColor: Colors.white,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ));
  }
}

class TestFlowDelegate extends FlowDelegate {
  EdgeInsets margin = EdgeInsets.zero;

  TestFlowDelegate({this.margin});

  @override
  void paintChildren(FlowPaintingContext context) {
    var x = margin.left;
    var y = margin.top;
    //计算每一个子widget的位置
    for (int i = 0; i < context.childCount; i++) {
      var w = context.getChildSize(i).width + x + margin.right;
      if (w < context.size.width) {
        context.paintChild(i,
            transform: new Matrix4.translationValues(x, y, 0.0));
        x = w + margin.left;
      } else {
        x = margin.left;
        y += context.getChildSize(i).height + margin.top + margin.bottom;
        //绘制子widget(有优化)
        context.paintChild(i,
            transform: new Matrix4.translationValues(x, y, 0.0));
        x += context.getChildSize(i).width + margin.left + margin.right;
      }
    }
  }

  @override
  getSize(BoxConstraints constraints) {
    //指定Flow的大小
    return Size(double.infinity, 500);
  }

  @override
  bool shouldRepaint(FlowDelegate oldDelegate) {
    return oldDelegate != this;
  }
}
